package com.lgcns.android2;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PhotoCursorAdapter extends CursorAdapter {

    private Context mContext;
    private LayoutInflater mInflater;
    final private BitmapFactory.Options mOptions;
    private BitmapCache mBitmapCache;

    public PhotoCursorAdapter(Context context, Cursor c) {
        super(context, c);

        mContext = context;
        mInflater = LayoutInflater.from(context);
        mOptions = new BitmapFactory.Options();
        mOptions.inSampleSize = 2;
        mBitmapCache = new BitmapCache(context, mOptions);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewCache cache = (ViewCache) view.getTag();

        ProfileItem item = cache.item;

        item.idNum = cursor.getInt(cursor.getColumnIndex(Constants.ID_NUM));
        item.title = cursor.getString(cursor.getColumnIndex(Constants.TITLE));
        item.name = cursor.getString(cursor.getColumnIndex(Constants.NAME));
        item.tel = cursor.getString(cursor.getColumnIndex(Constants.TEL));
        item.email = cursor.getString(cursor.getColumnIndex(Constants.EMAIL));
        item.location = cursor.getString(cursor.getColumnIndex(Constants.LOCATION));
        item.job = cursor.getString(cursor.getColumnIndex(Constants.JOB));
        item.manager = cursor.getString(cursor.getColumnIndex(Constants.MANAGER));

        Bitmap bm = mBitmapCache.get(cursor);
        
        ImageView photo = cache.photo;
        TextView photoName = cache.photoName;

        photo.setImageBitmap(bm);

        BitmapDrawable drawable = (BitmapDrawable) photo.getDrawable();
        drawable.setAntiAlias(true);
        
        photoName.setText(item.name + "  " + item.title);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = mInflater.inflate(R.layout.photo, parent, false);
  
        ViewCache cache = new ViewCache();
        cache.photo = (ImageView) view.findViewById(R.id.photo);  
        cache.photoName = (TextView) view.findViewById(R.id.photoName);
        cache.item = new ProfileItem();

        view.setTag(cache);

        return view;
    }

    public void invalidateBitmapCache(int idNum) {
        mBitmapCache.remove(idNum);
    }

    public class ViewCache {
        ImageView photo;
        TextView photoName;
        ProfileItem item;
    }

}
